package export

import (
	"apidoc2entity/model"
	"fmt"
	"os"
	"path"
)

func Export(ch <-chan *model.Product) <-chan *model.Product {
	out := make(chan *model.Product)
	go func() {
		defer close(out)
		for pro := range ch {
			err := os.MkdirAll(pro.FileDir, os.ModePerm)
			if err != nil {
				fmt.Println(err)
			}
			// 写入
			Write2File(path.Join(pro.FileDir, pro.FileName), pro.Data)
			//组装数据
			out <- pro
		}
	}()
	return out
}

func Write2File(path, data string) {
	f, err := os.Create(path)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer f.Close()
	l, err := f.WriteString(data)
	if err != nil {
		fmt.Println(err)
		f.Close()
		return
	}
	fmt.Println(l, "bytes written successfully")
	err = f.Close()
	if err != nil {
		fmt.Println(err)
		return
	}
}
